<?php
namespace app\common\model;
use app\user\model\User;
use app\user\model\UserAttribute;
use juhe\juhe;
use think\facade\Cache;
use think\Model;


class Comment extends TimeModel
{
    protected $updateTime = false;
    static function onAfterInsert()
    {
        self::clearCache();
    }

    static function onAfterUpdate()
    {
        self::clearCache();
    }
    static function clearCache()
    {
        if (Cache::has('comment_list')) {
            Cache::delete('comment_list');
        }
    }
    public function getIp2longAttr($value){
        return $value?long2ip($value):'';
    }
    public function setIp2longAttr($value){
        return ip2long($value);
    }
    public function setSubjectAttr($value, $data){
        $article=(new Article())->find($data['subject_id']);
        $this->set('subject',$value);
        $this->set('subject_title',$article->title);
    }


    public static function checkAuth($uid=0)
    {
        $config = sysconfig('comment');

        $model=new static();
        $todatTime=todayTime();
        if (@$config['interval_time']) {
            $interval=$config['interval_time'];
            $lastSend = $model
                ->where('ip2long',ip2long(request()->ip()))
                ->where('subject','ARTICLE')
                ->order('id', 'desc')
                ->limit(1)
                ->value('create_time');

            if($lastSend&&($lastSend + 60 * $interval)>time()) {
                return array('code' => -1, 'msg' => '频率过快，请稍后再试');
            }
        }

        if ($uid&&$config['user_day_max']) {
            $emailMax = $config['user_day_max'];
            $emailCount = $model
                ->where('create_time','>',$todatTime)
                ->where('user_id',$uid)
                ->count();
            if ($emailCount >= $emailMax) {
                return array('code' => -1, 'msg' => '每个用户每天限制发送' . $emailMax . '条评论');
            }
        }

        if ($config['ip_day_max']) {
            $ipMax = $config['ip_day_max'];
            $ipCount = $model
                ->where('create_time','>',$todatTime)
                ->where('ip2long',ip2long(request()->ip()))
                ->count();
            if ($ipCount >= $ipMax) {
                return array('code' => -1, 'msg' => '每个IP每天限制发布' . $ipMax . '条评论');
            }
        }
        return true;
    }

    static function getItems($type){
        $cacheName='comment_'.$type;
        $data=[];
        if(Cache::has($cacheName)){
            $data=Cache::get($cacheName);
        }else {
            switch ($type) {
                case 'list':
                    $limit=sysconfig('comment.show_new_num');
                    $data=static::where('status',1)
                        ->field('nickname,avatar,subject_id,subject_title,content,create_time')
                        ->order('id','desc')
                        ->limit($limit>0?$limit:10)
                        ->select();
                    $categorys = getJsonData('ArticleCategory', 'list');
                    $cate = array_column($categorys, 'alias', 'id');
                    foreach ($data as &$v) {
                        $artItem=Article::find($v['subject_id']);
                        $v['url'] = Article::detailUrl($v['subject_id'], $artItem?$artItem['category_id']:0, $cate);
                    }
                    Cache::set($cacheName,$data);
                    break;
            }
        }
        return $data;
    }

    public static function insertOne($content, $objectType, $objectId, $parentId = 0, $pid = 0,$status=1,$uid=0)
    {
        if ($pid == 0) {
            $rootId = $parentId;
        } else {
            $rootId = $parentId;
            $parentId = $pid;
        }
        $ip=Request()->ip();
        $nickanme='游客'.substr_replace_ext($ip,'*',4,4);
        $avatar='';
        if($uid) {
            $user=(new User())->find($uid);
            $nickanme=$user->nickname;
            $avatar=$user->avatar;
        }elseif($ip!='127.0.0.1'){
            $ipInfo=juhe::ipNew($ip);
            if($ipInfo['code']==1){
                $nickanme=$ipInfo['data']['City'].$ipInfo['data']['Isp'].'用户';
            }
        }
        $comment = (new self())->create([
            'content' => $content,
            'subject_id' => $objectId,
            'subject' => $objectType,
            'pid' => $parentId,
            'root_id' => $rootId,
            'status' => $status,
            'nickname' => $nickanme,
            'avatar' => $avatar,
            'support_num' => 0,
            'oppose_num' => 0,
            'ip2long' => $ip,
            'user_id' => $uid
        ]);
        (new Article())->where('id', $objectId)->inc('comment_num')->update();
        if($uid) {
            (new UserAttribute())->where('user_id', session('userid'))->inc('comment_num')->update();
        }
//        $comment->create_time=date('Y-m-d H:i:s',time());

        return $comment;
    }


}